//
//  ImageUpload.swift
//  EyeVisionForDoctors
//
//  Created by PMC on 2022/4/26.
//  Copyright © 2022 tao Tao. All rights reserved.
//

import UIKit

class YSGImageUpload {
    class func upload(image: UIImage, imageType: UploadImageType, complete: @escaping (_ code: HttpCode,_ model: UploadImgModel?,_ error: String?) -> Void) {
        let params = ["bucket": imageType.bucket]
        HttpTool.shared.request(api: ApiManager.getPresignedUrl(paras: params), model: String.self) { result in
            switch result {
            case .success(let model):
                guard let url = model.data,
                      !url.isEmpty else {
                          complete(.failure, nil, "上传图片错误,请稍后再试(-1)")
                          return
                      }
                uploadImageToS3(imageType: imageType, image: image, urlStr: url, complete: complete)
            case .failure(let error):
                complete(.failure, nil, error.errorValue)
            }
        }
    }
    
    /// 上传图片到 S3
    class private func uploadImageToS3(imageType: UploadImageType,
                                       image: UIImage,
                                       urlStr: String,
                                       complete: @escaping (_ code: HttpCode, _ model: UploadImgModel?, _ error: String?) -> Void) {
        let imageData = image.jpegData(compressionQuality: 1) ?? Data()
        
        guard let url = URL(string: urlStr) else {
            complete(.failure, nil, "图片上传失败,请稍后再试(-2)")
            return
        }
        var urlRequest = URLRequest(url: url)
        urlRequest.httpMethod = "PUT"
        urlRequest.httpBody = imageData
        
        let dataTask = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
            if error != nil {
                complete(.failure, nil, error?.localizedDescription)
            } else {
                guard let resourceId = urlStr.components(separatedBy: "?").first?.components(separatedBy: "/").last else {
                    complete(.failure, nil, "图片上传失败,请稍后再试(-3)")
                    return
                }
                saveImageToDataBase(objectName: resourceId, imageType: imageType, size: image.imageSize(), isIm: imageType == .chat ? 1 : 0, complete: complete)
            }
        }
        dataTask.resume()
        
    }
    
    /// 保存图片到数据库
    /// bucket: 1 - 病历图片  9 - 聊天图片  3 - 头像
    /// type:  15 - 病历图片 92 - 聊天图片 30 - 头像
    class private func saveImageToDataBase(objectName: String,
                                           imageType: UploadImageType,
                                           relationId: Int = -1,
                                           introduction: String = "image/png",
                                           size: Double,
                                           checkStatus: UploadImageStatus = .none,
                                           isIm: Int = 0,
                                           complete: @escaping (_ code: HttpCode, _ model: UploadImgModel?, _ error: String?) -> Void) {
        let params: [String: Any] = [
            "objectName": objectName,
            "bucket": imageType.bucket,
            "type": imageType.type,
            "relationId": relationId,
            "introduction": introduction,
            "size": size,
            "checkStatus": checkStatus.rawValue,
            "isIm": isIm
        ]
        HttpTool.shared.request(target: ApiManager.saveImageToDataBase(paras: params), success: { (json, code) in
            let model = UploadImgModel.deserialize(from: json["data"].description)
            complete(.success, model, json["message"].description)
        }) { error in
            complete(.failure, nil, error)
            
        }
    }
    
}
